package com.wechat.service.impl;

import com.wechat.entity.config.AppConfig;
import com.wechat.entity.constants.Constants;
import com.wechat.entity.dto.MessageSendDto;
import com.wechat.entity.dto.TokenUserInfoDto;
import com.wechat.entity.enums.*;
import com.wechat.entity.po.GroupInfo;
import com.wechat.entity.po.UserContact;
import com.wechat.entity.po.UserInfo;
import com.wechat.entity.po.UserInfoBeauty;
import com.wechat.entity.query.*;
import com.wechat.entity.vo.PaginationResultVO;
import com.wechat.entity.vo.UserInfoVO;
import com.wechat.exception.BusinessException;
//import com.wechat.mappers.GroupInfoMapper;
//import com.wechat.mappers.UserContactMapper;
import com.wechat.mappers.GroupInfoMapper;
import com.wechat.mappers.UserContactMapper;
import com.wechat.mappers.UserInfoBeautyMapper;
import com.wechat.mappers.UserInfoMapper;
import com.wechat.redis.RedisComponent;
//import com.wechat.service.ChatSessionUserService;
//import com.wechat.service.UserContactService;
import com.wechat.service.ChatSessionUserService;
import com.wechat.service.UserContactService;
import com.wechat.service.UserInfoService;
import com.wechat.utils.StringTools;
import com.wechat.websocket.MessageHandler;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 业务接口实现
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

    @Resource
    private AppConfig appConfig;

    @Resource
    private GroupInfoMapper<GroupInfo, GroupInfoQuery> groupInfoMapper;

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;

    @Resource
    private RedisComponent redisComponent;


    @Resource
    private ChatSessionUserService chatSessionUserService;

    @Resource
    private MessageHandler messageHandler;

    @Resource
    private UserContactService userContactService;

    @Resource
    private UserInfoBeautyMapper<UserInfoBeauty, UserInfoBeautyQuery> userInfoBeautyMapper;

    @Resource
    private ChatSessionUserServiceImpl chatSessionUserServiceImpl;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<UserInfo> findListByParam(UserInfoQuery param) {
        return this.userInfoMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(UserInfoQuery param) {
        return this.userInfoMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<UserInfo> findListByPage(UserInfoQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<UserInfo> list = this.findListByParam(param);
        PaginationResultVO<UserInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(UserInfo bean) {
        return this.userInfoMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<UserInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userInfoMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<UserInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userInfoMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(UserInfo bean, UserInfoQuery param) {
        StringTools.checkParam(param);
        return this.userInfoMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(UserInfoQuery param) {
        StringTools.checkParam(param);
        return this.userInfoMapper.deleteByParam(param);
    }

    /**
     * 根据UserId获取对象
     */
    @Override
    public UserInfo getUserInfoByUserId(String userId) {
        return this.userInfoMapper.selectByUserId(userId);
    }

    /**
     * 根据UserId修改
     */
    @Override
    public Integer updateUserInfoByUserId(UserInfo bean, String userId) {
        return this.userInfoMapper.updateByUserId(bean, userId);
    }

    /**
     * 根据UserId删除
     */
    @Override
    public Integer deleteUserInfoByUserId(String userId) {
        return this.userInfoMapper.deleteByUserId(userId);
    }

    /**
     * 根据Email获取对象
     */
    @Override
    public UserInfo getUserInfoByEmail(String email) {
        return this.userInfoMapper.selectByEmail(email);
    }

    /**
     * 根据Email修改
     */
    @Override
    public Integer updateUserInfoByEmail(UserInfo bean, String email) {
        return this.userInfoMapper.updateByEmail(bean, email);
    }

    /**
     * 根据Email删除
     */
    @Override
    public Integer deleteUserInfoByEmail(String email) {
        return this.userInfoMapper.deleteByEmail(email);
    }

    /**
     * 注册
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(String email, String nickName, String password) {
        //校验邮箱
        if(StringTools.checkEmail(email)){
            throw new BusinessException("邮箱格式不正确");
        }
        UserInfo userInfo = userInfoMapper.selectByEmail(email);
        if(userInfo!=null){
            throw new BusinessException("邮箱账号已经存在");
        }

        Date curDate = new Date();
        String userId = StringTools.getUserId();//生成用户ID

        //查询邮箱是否需要设置靓号
        UserInfoBeauty beautyAccount = userInfoBeautyMapper.selectByEmail(email);
        //判断是否可以使用靓号 1.数据库中存在该邮箱的靓号记录 2.该靓号记录状态为未使用
        Boolean useBeautyAccount = false;
        if(beautyAccount!=null){
            useBeautyAccount = BeautyAccountStatusEnum.NO_USE.getStatus().equals(beautyAccount.getStatus());
        }
        //如果可以使用靓号，则使用该靓号作为用户ID---"U"+beautyUserId
        if(useBeautyAccount){
            String beautyUserId = beautyAccount.getUserId();
            userId = UserContactTypeEnum.USER.getPrefix() + beautyUserId;
        }

        //创建用户
        userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickName(nickName);
        userInfo.setEmail(email);
        userInfo.setPassword(StringTools.encodeByMD5(password));
        userInfo.setCreateTime(curDate);
        userInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
        userInfo.setLastOffTime(curDate.getTime()); //第一次注册时，离线时间设置为当前时间
        userInfo.setJoinType(JoinTypeEnum.APPLY.getType());
        userInfoMapper.insert(userInfo);

        //更新靓号状态
        if (useBeautyAccount) {
            UserInfoBeauty updateBeauty = new UserInfoBeauty();
            updateBeauty.setStatus(BeautyAccountStatusEnum.USEED.getStatus());//设置状态：已使用
            userInfoBeautyMapper.updateById(updateBeauty, beautyAccount.getId());
        }

        //添加机器人好友
        userContactService.addContact4Robot(userId);

    }


    /**
     * 登录
     */
    @Override
    public UserInfoVO login(String email, String password) {
        //1.先查询用户
        UserInfo userInfo = userInfoMapper.selectByEmail(email);
        //1.1.判断用户存在
        if(userInfo == null || !userInfo.getPassword().equals(StringTools.encodeByMD5(password))){
            throw new BusinessException("账号或密码错误");
        }
        //1.2.判断用户状态（兼容对管理员的设定）
        if(userInfo.getStatus().equals(UserStatusEnum.DISABLE.getStatus())){
            throw new BusinessException("账号已禁用");
        }

        //查询联系人---redis中仅保存联系人状态是好友的，拉黑的保存在数据库中，但是redis中不沾边
        UserContactQuery contactQuery = new UserContactQuery();
        contactQuery.setUserId(userInfo.getUserId());
        contactQuery.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        List<UserContact> contactList = userContactMapper.selectList(contactQuery);
        //获取联系人id集合(流处理)
        Stream<String> idList = contactList.stream().map(item -> item.getContactId());
        List<String> contactIdList = idList.collect(Collectors.toList());
        //将联系人id集合保存到redis
        redisComponent.cleanUserContact(userInfo.getUserId());//删除旧数据
        if (!contactIdList.isEmpty()) {
            redisComponent.addUserContactBatch(userInfo.getUserId(), contactIdList);
        }


        //封装用户信息（用于存redis）
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto(userInfo);

        //逻辑：1.获取用户心跳 2.判断是否已登录 3.未登录生成token并保存到redis
        Long lastHeartBeat = redisComponent.getUserHeartBeat(tokenUserInfoDto.getUserId());
        if(lastHeartBeat != null){
            throw new BusinessException("此账号已经在别处登录，请退出后再登录");
        }

        //生成 token ：userId + 20位随机字符串
        String token = StringTools.encodeByMD5(tokenUserInfoDto.getUserId() + StringTools.getRandomString(Constants.LENGTH_20));
        tokenUserInfoDto.setToken(token);
        //保存登录信息到redis中
        redisComponent.saveTokenUserInfoDto(tokenUserInfoDto);

        //封装返回数据
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(userInfo, userInfoVO);
        userInfoVO.setToken(tokenUserInfoDto.getToken());
        userInfoVO.setAdmin(tokenUserInfoDto.getAdmin());
        return userInfoVO;
    }

    /**
     * 封装登录信息（userId,昵称，是否是管理员）
     */
    private TokenUserInfoDto getTokenUserInfoDto(UserInfo userInfo) {
        TokenUserInfoDto tokenUserInfoDto = new TokenUserInfoDto();
        tokenUserInfoDto.setUserId(userInfo.getUserId());
        tokenUserInfoDto.setNickName(userInfo.getNickName());

        //判断是否是管理员
        String adminEmails = appConfig.getAdminEmails();
        String[] adminEmailArray = adminEmails.split(",");
        if(!StringTools.isEmpty(adminEmails) && ArrayUtils.contains(adminEmailArray, userInfo.getEmail())){
            tokenUserInfoDto.setAdmin(true);
        }else{
            tokenUserInfoDto.setAdmin(false);
        }
        return tokenUserInfoDto;
    }


    /**
     * 更新用户信息---头像上传 昵称更新
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(UserInfo userInfo, MultipartFile avatarFile, MultipartFile avatarCover) throws IOException {
        //头像上传存储路径---同一个用户头像保存路径是固定的
        if(avatarFile != null){
            //确保头像存储路径存在
            String baseFolder = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE;//头像保存路径
            //new File(完整的文件路径字符串)
            File targetFileFolder = new File(baseFolder + Constants.FILE_FOLDER_AVATAR_NAME);//创建头像文件路径
            if (!targetFileFolder.exists()) {
                targetFileFolder.mkdirs();
            }
            //保存头像
            String filePath = targetFileFolder.getPath() + "/" + userInfo.getUserId() + Constants.IMAGE_SUFFIX;//设置头像文件保存路径
            avatarFile.transferTo(new File(filePath));//保存头像到指定路径
            avatarCover.transferTo(new File(filePath + Constants.COVER_IMAGE_SUFFIX));//保存缩略图头像到指定路径
        }
        //从数据库中获取用户信息更新前的完整信息
        /*
        为什么要先查，这里有两个细节：
        1.对比昵称是否更新
        2.在事务中（只有写数据库才会触发事务）查询数据，读取的是当前事务中已修改但未提交的数据，而非原始数据
         */
        UserInfo dbUserInfo = userInfoMapper.selectByUserId(userInfo.getUserId());
        //更新用户信息
        userInfoMapper.updateByUserId(userInfo, userInfo.getUserId());
        //检测昵称的更新
        String contactNameUpdate = null;
        if (!dbUserInfo.getNickName().equals(userInfo.getNickName())) {
            contactNameUpdate = userInfo.getNickName();
        }
        if(contactNameUpdate == null){
            return;
        }

        //更新redis中的昵称
        TokenUserInfoDto tokenUserInfo= redisComponent.getTokenUserInfoDtoByUserId(userInfo.getUserId());
        tokenUserInfo.setNickName(contactNameUpdate);
        redisComponent.saveTokenUserInfoDto(tokenUserInfo);
        //更新会话信息中的昵称信息
        chatSessionUserService.updateRedundanceInfo(contactNameUpdate, userInfo.getUserId());

    }

    /**
     * 更新用户状态
     */
    @Override
    public void updateUserStatus(Integer status, String userId) {
        UserStatusEnum userStatusEnum = UserStatusEnum.getByStatus(status);
        if (userStatusEnum == null) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        UserInfo updateInfo = new UserInfo();
        updateInfo.setStatus(userStatusEnum.getStatus());
        userInfoMapper.updateByUserId(updateInfo, userId);
    }

    /**
     * 强制下线
     */
    @Override
    public void forceOffLine(String userId) {
        //强制下线
        MessageSendDto messageSendDto = new MessageSendDto();
        messageSendDto.setMessageType(MessageTypeEnum.FORCE_OFF_LINE.getType());
        messageSendDto.setContactId(userId);
        messageSendDto.setContactType(UserContactTypeEnum.USER.getType());
        messageHandler.sendMessage(messageSendDto);

   }
}